package com.baoyouqun.API.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.mapper.UserRecommendMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserRecommendServiceImpl extends ServiceImpl<UserRecommendMapper, UserRecommend> implements UserRecommendService {
    @Resource
    private UserRecommendMapper userRecommendMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(String userId, List<String> recommendUserIdList) {
        // 构建实体
        UserRecommend record = new UserRecommend();
        record.setUserId(userId);
        record.setRecommendUserIds(recommendUserIdList); // 自动转换为逗号分隔字符串
        record.setUpdateTime(LocalDateTime.now());

        // 插入或更新
        return getBaseMapper().insertOrUpdate(record);
    }

    @Override
    public List<String> getRecommendUserIds(String userId) {
        // 1. 查询当前用户的推荐记录
        UserRecommend record = getOne(new LambdaQueryWrapper<UserRecommend>()
                .eq(UserRecommend::getUserId, userId));
        if (record == null) {
            return List.of(); // 无推荐时返回空列表
        }

        // 2. 获取原始推荐用户ID列表（自动转换为List<String>）
        List<String> originalRecommendIds = record.getRecommendUserIds();

        // 3. 打乱逻辑：仅当列表长度>1时才打乱（长度≤1打乱无意义）
        if (CollUtil.isEmpty(originalRecommendIds) || originalRecommendIds.size() <= 1) {
            return originalRecommendIds; // 空列表或仅1个元素，直接返回
        }

        // 4. 复制列表后打乱（避免修改原列表，保证线程安全和数据一致性）
        // 原因：若原列表是不可变列表（如List.of()）或其他地方复用，直接打乱会引发异常或数据污染
        List<String> shuffledRecommendIds = new ArrayList<>(originalRecommendIds);
        Collections.shuffle(shuffledRecommendIds); // 原地打乱列表

        // 5. 返回打乱后的列表
        return shuffledRecommendIds;
    }

    @Override
    public void deleteByUserId(String targetUserId) {
        remove(new LambdaQueryWrapper<UserRecommend>().eq(UserRecommend::getUserId, targetUserId));
    }
}